package com.iye.puretennis.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.*;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import com.iye.puretennis.R;
import com.iye.puretennis.activity.MainTabsActivity;
import com.iye.puretennis.activity.TabsIndicatorActivity;
import com.iye.puretennis.custom.HuaWenHuPoTextView;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.DBManager;
import com.iye.puretennis.helper.ImageHelper;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * Author: Chuanbao on 2014/11/20.
 */
public abstract class TabFragment extends ProgressFragment {

    protected Context mContext;

    protected DBManager dbManager;

    protected UserToken token;

    protected String json;

    protected View mainView;

    protected ImageButton backButton;

    protected HuaWenHuPoTextView headerText;

    protected int width;

    protected int height;

    protected MainTabsActivity fragmentActivity;

    private Handler mHandler;

    private Runnable mShowContentRunnable = new Runnable() {

        @Override
        public void run() {
            setContentShownNoAnimation(true);
        }

    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Setup content view
        setContentView(mainView);
        // Setup text for empty content
        setEmptyText(R.string.empty);
        obtainData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mHandler.removeCallbacks(mShowContentRunnable);
    }

    private void obtainData() {
        // Show indeterminate progress
        setContentShownNoAnimation(false);

        updateUI();

        mHandler = new Handler();
        mHandler.postDelayed(mShowContentRunnable, 500);
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity.getApplicationContext();
        dbManager = new DBManager(activity);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {


        DisplayMetrics dm = new DisplayMetrics();

        fragmentActivity = (MainTabsActivity) getActivity();

        fragmentActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);


        width = dm.widthPixels;

        height = dm.heightPixels;

        token = dbManager.retrieveCurrentUser();

        mainView = inflater.inflate(getViewId(), null);

        backButton = (ImageButton) mainView.findViewById(R.id.back_button);

        if (backButton != null) {

            backButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isParent()) {
                        fragmentActivity.onBackPressed();
                    } else {
                        onBackPressed();
                    }


                }
            });
        }

        headerText = (HuaWenHuPoTextView) mainView.findViewById(R.id.header_text);

        onCustomCreateView(inflater);


        return inflater.inflate(R.layout.fragment_progress, container, false);

    }


    public abstract int getViewId();

    public abstract int getSourceId();

    public boolean isParent() {
        return false;
    }


    /**
     * 更新页面
     */
    public abstract void updateUI();

    public void onCustomCreateView(LayoutInflater inflater) {

    }

    protected void goFragment(int sourceId, String tag, Class targetFragmentClazz, Bundle args, boolean alwaysNewTarget, String userGuid) {
        if (token != null && token.getGuid().equals(userGuid)) {
            ((TabsIndicatorActivity) getActivity()).goTab(3);
        } else {
            goFragment(sourceId, tag, targetFragmentClazz, args, alwaysNewTarget);
        }
    }


    @SuppressWarnings({"rawtypes", "unchecked"})
    protected void goFragment(int sourceId, String tag, Class targetFragmentClazz, Bundle args, boolean alwaysNewTarget) {
        FragmentManager fm = getChildFragmentManager();
        // 开启Fragment事务
        FragmentTransaction transaction = fm.beginTransaction();

        Fragment fragment = null;
        if (!alwaysNewTarget) {
            fragment = fm.findFragmentByTag(tag);
        }

        if (fragment == null) {
            Constructor constructor;
            try {
                constructor = targetFragmentClazz.getConstructor(new Class[0]);
                fragment = (Fragment) constructor.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
        }
        if (args != null) {
            fragment.setArguments(args);
        }
        transaction.replace(sourceId, fragment, tag).
                setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
                .addToBackStack(null).commit();
    }

    protected void onBackPressed() {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        int count = fm.getBackStackEntryCount();
        if (count > 0) {
            fm.popBackStack();
        }
        transaction.commit();
    }

    //enable为true时，菜单添加图标有效，enable为false时无效。4.0系统默认无效
    protected void setIconEnable(Menu menu, boolean enable) {
        try {
            Class<?> clazz = Class.forName("com.android.internal.view.menu.MenuBuilder");

            Method m = clazz.getDeclaredMethod("setOptionalIconsVisible", boolean.class);

            m.setAccessible(true);

            //MenuBuilder实现Menu接口，创建菜单时，传进来的menu其实就是MenuBuilder对象(java的多态特征)
            m.invoke(menu, enable);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void showPopupMenu(View view, int menuRes, android.widget.PopupMenu.OnMenuItemClickListener onMenuItemClickListener) {
        PopupMenu pop = new PopupMenu(getActivity(), view);

        Menu menu = pop.getMenu();

        setIconEnable(menu, true);

        pop.getMenuInflater().inflate(menuRes, menu);

        pop.setOnMenuItemClickListener(onMenuItemClickListener);

        pop.show();
    }

    protected void loadUserImage(String userGuid, ImageView imageView) {

        DisplayImageOptions options = ImageHelper.createDisplayImageOptions(fragmentActivity.getBuilder(), userGuid);

        ImageLoader.getInstance().displayImage(ImageHelper.getImageUri(userGuid), imageView, options);
    }
}
